package common;

import java.util.*;

/**
 * @program: hty
 * @description: 抽奖
 * @author: daiyuanbao
 * @create: 2021-08-03 17:33
 */
public class luckyDrawUtil {

    /**
     * 抽奖方法
     * <br/>
     * create by: leigq
     * <br/>
     * create time: 2019/7/5 23:08
     * @param orignalRates 商品中奖概率列表，保证顺序和实际物品对应
     * @return 中奖商品索引
     */
    public static int lottery(List<Double> orignalRates) {

        if (orignalRates == null || orignalRates.isEmpty()) {
            return -1;
        }

        int size = orignalRates.size();

        // 计算总概率，这样可以保证不一定总概率是1
        double sumRate = 0d;
        for (double rate : orignalRates) {
            sumRate += rate;
        }

        // 计算每个物品在总概率的基础下的概率情况
        List<Double> sortOrignalRates = new ArrayList<>(size);
        Double tempSumRate = 0d;
        for (double rate : orignalRates) {
            tempSumRate += rate;
            sortOrignalRates.add(tempSumRate / sumRate);
        }

        // 根据区块值来获取抽取到的物品索引
        double nextDouble = Math.random();
        sortOrignalRates.add(nextDouble);
        Collections.sort(sortOrignalRates);

        return sortOrignalRates.indexOf(nextDouble);
    }
    public static void main(String[] args) {

        List<Map<String,Object>> mapList = new ArrayList<>();
        Map<String,Object> map=null;

        map=new HashMap<>();
        map.put("index",1);
        map.put("name","谢谢参与");
        map.put("no","P1");
        map.put("probability",0.5);
        mapList.add(map);
        map=new HashMap<>();
        map.put("index",2);
        map.put("name","一等奖");
        map.put("no","P2");
        map.put("probability",0.5);
        mapList.add(map);
        // 存储概率
        List<Double> orignalRates = new ArrayList<>();
        for (Map<String,Object> gift : mapList) {
            double probability = (Double) gift.get("probability");
            if (probability < 0) {
                probability = 0;
            }
            orignalRates.add(probability);
        }

        // 统计
        Map<Integer, Integer> count = new HashMap<>();

        // 测试次数
        double num = 1;
        for (int i = 0; i < num; i++) {
            int orignalIndex = lottery(orignalRates);
            Integer value = count.get(orignalIndex);
            System.out.println(value);
            count.put(orignalIndex, value == null ? 1 : value + 1);
        }

        for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
            System.out.println(mapList.get(entry.getKey()) + ", 命中次数=" + entry.getValue() + ", 实际概率="
                    + entry.getValue() / num);
        }
    }

}
